<?php

declare(strict_types=1);

namespace App\Controller;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Library\Common;
use App\Model\data\CurrentShopData;
use App\Model\FlyShop;
use App\Service\AreainfoService;
use App\Service\ShopSendAddressService;
use Hyperf\Validation\Rule;
use Hyperf\DbConnection\Db;
Use Hyperf\Di\Annotation\Inject;
use Psr\Http\Message\ResponseInterface;

class SendAddressController extends AbstractController
{
    /**
     * @Inject
     * @var ShopSendAddressService
     */
    private $sendAddress;

    /**
     * @Inject
     * @var AreainfoService
     */
    private $areainfo;

    public $shop_info;
    public function __construct()
    {
        $this->shop_info = CurrentShopData::getData();
    }

    public function list()
    {
//        不分页
        // 关键字：名称
        $params= $this->request->inputs(['link_name','address_info','phone']);
        return $this->jsonResponse->success($this->sendAddress->index($params, $this->shop_info->id), '获取列表成功');
    }

    public function get_default_addr()
    {
        // 关键字：名称
        return $this->jsonResponse->success($this->sendAddress->get_default_addr($this->shop_info->id), '获取列表成功');
    }

    public function add()
    {

        $params = $this->request->inputs(['link_name','phone','address_info','street_id']);
        $this->validation(
            $params,
            [
                'link_name' => [
                    "required",
                    "string",
                    "max:50",
                ],
                'phone' => [
                    "required",
                    "string",
                    "max:20",
                ],
                'address_info' => [
                    "required",
                    "max:255",
                ],
                'street_id' => [
                    "required",
                    "integer",
                   Rule::exists('areainfo','id')->where('level',5)
                ],
            ],
        );
        Db::beginTransaction();
        $params['created_at'] = date('Y-m-d H:i:s');
        $params['create_by'] = parent::getAdminId();
        $params['shop_id'] = $this->shop_info->id;
        $params['is_shop_addr'] = 0;

        // 获取街道完整名称
        $street_arr = array_column($this->areainfo->getFullAddress($params['street_id']), 'name');
        $params['street_str'] = implode('', $street_arr);
        $locate = Common::getAddressLocation($params['street_str'] . $params['address_info']);
        $params['lat'] = $locate['lat'] ?? 0;
        $params['lng'] = $locate['lng'] ?? 0;
        try {
            $address_id =  $this->sendAddress->address_insert($params);
            if($address_id){
                Db::commit();
                return $this->jsonResponse->success($address_id,'添加成功');
            }else{
                Db::rollBack();
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'添加失败');
            }
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'添加失败'.$exception->getMessage());
        }

    }

    public function edit()
    {
        $params = $this->request->inputs(['id','link_name','phone','address_info','lng','lat','street_id','street_str']);
        $this->validation(
            $params,
            [
                'id' => [
                    "required",
                    "integer",
                    Rule::exists('fly_shop_send_address','id')
                    ->where('shop_id',$this->shop_info->id)
                    ->where('is_shop_addr',0)
                    ->whereNull('deleted_at'),
                ],
                'link_name' => [
                    "required",
                    "string",
                    "max:50",
                ],
                'phone' => [
                    "required",
                    "string",
                    "max:20",
                ],
                'address_info' => [
                    "required",
                    "max:255",
                ],
                'street_id' => [
                    "required",
                    "integer",
                    Rule::exists('areainfo','id')->where('level',5)
                ],
            ],
            );
        Db::beginTransaction();
        $params['updated_at'] = date('Y-m-d H:i:s');
        $params['update_by'] = parent::getAdminId();
        // 获取街道完整名称
        $street_arr = array_column($this->areainfo->getFullAddress($params['street_id']), 'name');
        $params['street_str'] = implode('', $street_arr);
        $locate = Common::getAddressLocation($params['street_str'] . $params['address_info']);
        $params['lat'] = $locate['lat'] ?? 0;
        $params['lng'] = $locate['lng'] ?? 0;
        try {
            $result =  $this->sendAddress->update_address($params);
            if($result){
                Db::commit();
                return $this->jsonResponse->success([],'修改成功');
            }else{
                Db::rollBack();
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'修改失败');
            }
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'修改失败'.$exception->getMessage());
        }
    }

    public function detail()
    {
        $id = $this->request->input('id');
        $this->validation(
            ['id'=>$id],
            [
                'id' => [
                    'required',
                    'integer',
                    Rule::exists('fly_shop_send_address','id')->whereNull('deleted_at'),
                ],
            ],
            );
        try{
            return $this->jsonResponse->success($this->sendAddress->info(intval($id)),'信息返回');
        } catch (\Throwable $exception) {
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'不存在或已删除：'.$exception->getMessage());
        }
    }
    public function del()
    {
        $ids = $this->request->input('ids');
        $this->validation(
            ['ids'=>$ids],
            [
                'ids' => 'required|array',
                'ids.*' => [
                    'required',
                    'integer',
                    'min:0',
                    Rule::exists('fly_shop_send_address','id')->whereNull('deleted_at'),
                ],
            ],
            [
                'ids.*.unique'  =>'有关联数据，不可删除',
            ]
        );
        try{
            $this->sendAddress->deleteByUser($ids,$this->getAdminId());
            return $this->jsonResponse->success([],'删除成功');
        } catch (\Throwable $exception) {
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'删除失败');
        }
    }
}